package org.sang.controller.member;

import com.github.pagehelper.Page;
import org.sang.bean.Member;
import org.sang.service.IMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/memberInfo")
public class MemberController {

    @Autowired
    private IMemberService memberService;

    @RequestMapping(value = "/member", method = RequestMethod.POST)
    public ResponseEntity add(@RequestBody Member member) {
        return ResponseEntity.ok(memberService.add(member));
    }

    @RequestMapping(value = "/member/{id}", method = RequestMethod.GET)
    public ResponseEntity<Member> getMemebrById(@PathVariable String id) {
        return ResponseEntity.ok(memberService.getMemberById(id));
    }

    @RequestMapping(value = "/member/list", method = RequestMethod.POST)
    public ResponseEntity<Map<String, Object>> getMemebrListByPage(
        @RequestBody Member member, @RequestParam(defaultValue = "1") Integer pageNum,
        @RequestParam(defaultValue = "10") Integer pageSize) {

        Map<String, Object> result = new HashMap<>();
        Page<Member> page = memberService.getMemberListByPage(pageNum, pageSize, member);
        result.put("result", page.getResult());
        result.put("total", page.getTotal());
        return ResponseEntity.ok(result);
    }


    @RequestMapping(value = "/member/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Void> delete(@PathVariable String id) {
        memberService.delete(id);
        return ResponseEntity.ok().build();
    }

    @RequestMapping(value = "/member/{id}", method = RequestMethod.PUT)
    public ResponseEntity update(@RequestBody Member member, @PathVariable String id) {
        return ResponseEntity.ok(memberService.update(member, id));
    }
}
